<?php
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');
require_once('../../_inc/class.rglFileCsv.php');

$aExp = array();
if (reqVar('azione')=='upload')  {
	$msgPag .= uploadBil();
}
if (reqVar('azione')=='aggi' || reqVar('azione')=='sost')  {
	$msgPag .= importBil();
}

$cmdL = "";


$cmdR = '';
if (reqVar('file_caricato')!='') { 
	$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('sost');\">sostituisci</a>";
		$cmdR .= "&nbsp;&nbsp;&nbsp;";
	$cmdR .= "<a class=\"cmd1\" href=\"javascript:submAz('aggi');\">aggiorna</a>";
}
$cmdR .= cmdTorna(); 
testaHtml('',  $msgPag, 'ratg');
echo getHtmlForm();
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('azione','...');
echo getHtmlHidden('file_caricato');
echo getHtmlHidden('file_orig');
echo getHtmlHidden('id');
?>
<script language="JavaScript" type="text/javascript">
  	function submAz(az) {
  		document.frm1.azione.value = az;
  		document.frm1.submit();
  	}
</script>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="tit1" colspan='2'>Importazione Set Dati</td>
   </tr>
   <tr>
      <td class="lab1" colspan='1' align='left'>File setDati_xxx.ser</td>
      <td class="txt1" colspan='1' align='left'>
<?
echo getHtmlFile('file_ser', 80);
echo "&nbsp;&nbsp;&nbsp;";
if (reqVar('file_caricato')=='') { 
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">upload</a>";
} else {
	echo "<a class=\"cmd1\" href=\"javascript:submAz('upload');\">nuovo upload</a>";
}
?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='1'  width='20%'>File caricato</td>
      <td class="txt1" colspan='1'  width='80%'>
      	<?=reqVar('file_orig');?>
      </td>
   </tr>
</table>
<table class="cmd1" border="0" cellpadding="3" cellspacing="1" width="100%">
   <tr>
      <td class="cmd1" align="left">
         <?=$cmdL?>
      </td>
      <td class="cmd1" align="right">
         <?=$cmdR?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";
codaHtml();
exit();

function importBil() {
	global $objDB, $objSess;
	$msg = '';
	$aDefDati = array();
	$sSql = "SELECT str_def_dati, str_dati FROM rgl_bilancio WHERE id_bil = ".reqVar('id');
	$objDB->query($sSql);
	$aRec = $objDB->fetch();
	if (!$aRec) {
		return 'no bil. '.reqVar('id');
	}
	$aDefDati = unsgzu($aRec['str_def_dati']);
	if (reqVar('azione')=='aggi') {
		$aDati = unsgzu($aRec['str_dati']);
	} else {
		$aDati = array();
	}
	$pathFileCar = RGL_FS_TEMP_DIR."/".reqVar('file_caricato');	
	$oCsv = new rglFileCsv($pathFileCar,'r',true);
	if ($oCsv->codEsito != '200') {
		return "file non conforme o corrotto - ".$oCsv->desEsito."<br>";
	}
	$aX = $oCsv->read();
	if (!isset($aX['codice']) || !isset($aX['valore'])) {
		return "manca colonna codice e/o valore<br>";
	}
	$msg = '';
	while($aX) {
		if (str2num($aX['valore'])!==false 
		&& isset($aDefDati[strtoupper(trim($aX['codice']))])) {
			$aDati[strtoupper(trim($aX['codice']))] = str2num($aX['valore']);
		} else {
			dbg_($aX['codice']."=".$aX['valore']); //non dovrebbe passare
		}
		$aX = $oCsv->read();
	}
	$sSql = "UPDATE rgl_bilancio SET str_dati = '".asgzcser($aDati)."'"
		." WHERE id_bil = ".reqVar('id');
	$objDB->exec($sSql);
	header("Location: ".urlTorna());
	return "???";
}

function uploadBil() {
	global $objDB, $objSess;
	$aExp = array();
	if (!isset($_FILES['file_ser']) || $_FILES['file_ser']['tmp_name'] == '') {
		$_REQUEST['file_caricato'] = '';
		$_REQUEST['file_orig'] = '';
		return "nessun file caricato<br>";
	}
	$dh = opendir(RGL_FS_TEMP_DIR);
	while($fn = readdir($dh)) {
		if (substr($fn,0,15)=='bil_import_'
		&& filemtime(RGL_FS_TEMP_DIR."/".$fn) < (time()-3600*24)) {
			unlink(RGL_FS_TEMP_DIR."/".$fn);
		}
	}
	$aDefDati = array();
	$sSql = "SELECT str_def_dati FROM rgl_bilancio WHERE id_bil = ".reqVar('id');
	$objDB->query($sSql);
	$aRec = $objDB->fetch();
	if (!$aRec) {
		return 'no bil. '.reqVar('id');
	}
	$aDefDati = unsgzu($aRec['str_def_dati']);
	
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	$oCsv = new rglFileCsv($_FILES['file_ser']['tmp_name'],'r',true);
	if ($oCsv->codEsito != '200') {
		$_REQUEST['file_caricato'] = '';
		return "file non conforme o corrotto - ".$oCsv->desEsito."<br>";
	}
	$aX = $oCsv->read();
	if (!isset($aX['codice']) || !isset($aX['valore'])) {
		$_REQUEST['file_caricato'] = '';
		return "manca colonna codice e/o valore<br>";
	}
	$msg = '';
	while($aX) {
		if (str2num($aX['valore'])===false) {
			$msg .= "codice ".$aX['codice']." valore errato<br>";
		}
		if (!isset($aDefDati[strtoupper(trim($aX['codice']))])) {
			$msg .= "codice ".$aX['codice']." inesistente<br>";
		}
		$aX = $oCsv->read();
	}
	if ($msg != '') return $msg;
	$fileCar = "bil_import_".uniqid();
	$pathFileCar = RGL_FS_TEMP_DIR."/".$fileCar;
	copy($_FILES['file_ser']['tmp_name'],$pathFileCar);
	$_REQUEST['file_caricato'] = $fileCar;
	$_REQUEST['file_orig'] = $_FILES['file_ser']['name'];
	return "file caricato<br>";
}
